package com.icrazy.platform.dao.impl;

import java.util.List;

import org.apache.ibatis.session.RowBounds;
import org.mybatis.spring.support.SqlSessionDaoSupport;

import com.icrazy.platform.common.page.Page;
import com.icrazy.platform.dao.PlatformDao;
import com.icrazy.platform.exception.DaoException;
import com.icrazy.platform.exception.Ecode;
import com.icrazy.platform.util.Ts;

@SuppressWarnings("rawtypes")
public class PlatformDaoImpl extends SqlSessionDaoSupport implements PlatformDao {

	public static final String INSERT = ".insert";

	public static final String UPDATE = ".update";

	public static final String DELETE = ".delete";

	public static final String COUNT = ".count";

	public static final String LIST = ".list";

	public static final String LINE = ".line";

	public static final String PAGE = ".page";

	public PlatformDaoImpl() {

	}

	public void insert(String id, Object obj) {
		try {
			getSqlSession().insert(Ts.postFix(id, INSERT), obj);
		} catch (Exception e) {
			throw new DaoException(Ecode.DAO_INSERT, e.getCause(), id);
		}
	}

	public void update(String id, Object obj) {
		try {
			getSqlSession().update(Ts.postFix(id, UPDATE), obj);
		} catch (Exception e) {
			throw new DaoException(Ecode.DAO_UPDATE, e.getCause(), id);
		}
	}

	public void delete(String id, Object obj) {
		try {
			getSqlSession().delete(Ts.postFix(id, DELETE), obj);
		} catch (Exception e) {
			throw new DaoException(Ecode.DAO_DELETE, e.getCause(), id);
		}
	}

	public Object queryForObject(String id, Object obj) {
		Object rs = null;
		try {
			rs = getSqlSession().selectOne(Ts.postFix(id, LINE), obj);
		} catch (Exception e) {
			throw new DaoException(Ecode.DAO_QUERY_OBJECT, e.getCause(), id);
		}
		return rs;
	}

	public List queryForList(String id, Object obj) {
		List rs = null;
		try {
			rs = getSqlSession().selectList(Ts.postFix(id, LIST), obj);
		} catch (Exception e) {
			throw new DaoException(Ecode.DAO_QUERY_LIST, e.getCause(), id);
		}
		return rs;
	}

	@Override
	public List queryForPage(String id, Object obj, Page page) {
		List rs = null;
		try {
			rs = getSqlSession().selectList(id, obj, new RowBounds(page.getFirst(), page.getPageSize()));
		} catch (Exception e) {
			throw new DaoException(Ecode.DAO_QUERY_PAGE, e.getCause(), id);
		}
		return rs;
	}
}
